//
//  UploadShiTiQKCJViewController.m
//  MyProject
//
//  Created by Pei on 16/7/31.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "UploadShiTiQKCJViewController.h"
#import "IHRefreshTableView.h"
//#import "CheckAndAcceptCell.h"
#import "MultiSelectTableViewCell.h"
#import "QualityScanViewController.h"
//#import "GongXuDetailViewController.h"
#import "ShiTiQKCJCell.h"
#import "ShiTiQKCJDetailViewController.h"
#import "UploadShiTiQKCJDetailViewController.h"
#import "UserInfo.h"
#import "RequestPostUploadHelper.h"
#import "MBProgressHUD.h"
#import "AddShiTiCJFromUploadViewController.h"

@interface UploadShiTiQKCJViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    IHRefreshTableView *_myTable;
    UIView *_headerView;
    
    UIButton *_rightBtn;
    
    UIControl *_addControl;
    UIView *_addView;
    
    NSString *_currentAction;
    
    NSArray *dataArray;
    
    NSString *TMP_UPLOAD_IMG_PATH;
    
    MBProgressHUD *progressHUD;
}

@end

@implementation UploadShiTiQKCJViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TMP_UPLOAD_IMG_PATH = @"";
    
    dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:ShiTiQKCJ_Save];
    
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 22)];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [_rightBtn addTarget:self action:@selector(rightBtnAcion) forControlEvents:UIControlEventTouchUpInside];
    if (dataArray != nil && dataArray.count >0) {
        [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    }
    //[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
    
    //    _selFlags = [[NSMutableArray alloc] initWithCapacity:3];
    //    for (int i = 0; i < dataArray.count; i++)
    //    {
    //        [_selFlags addObject:[NSNumber numberWithBool:YES]];
    //    }
    
    
    
    [self initTableView];
    //[self initTableHeaderView];
    
    _addControl = [[UIControl alloc] init];
    _addControl.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [_addControl addTarget:self action:@selector(addControlAction) forControlEvents:UIControlEventTouchUpInside];
    _addControl.backgroundColor = kBtnBackgroundColor;
    [self.view addSubview:_addControl];
    
    //02edit@3x
    UILabel *btnTitle = [[UILabel alloc] initWithFrame:CGRectMake((kDeviceWidth-107)/2.0f, (_addControl.height-Home_Big_Size)/2.0f, 107, Home_Big_Size)];
    btnTitle.textColor = kWhiteColor;
    btnTitle.text = @"+实体采集情况";
    btnTitle.font = kAppFont(Home_Big_Size);
    [_addControl addSubview:btnTitle];
    
    _addView = [[UIView alloc] init];
    _addView.hidden = YES;
    _addView.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [self.view addSubview:_addView];
    
    //114 122 162
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [cancleBtn setBackgroundColor:kRGB(114, 122, 162)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = kAppFont(Home_Big_Size);
    cancleBtn.tag = 116;
    [cancleBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:cancleBtn];
    
    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    uploadBtn.frame = CGRectMake(kDeviceWidth/3.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [uploadBtn setBackgroundColor:kBtnBackgroundColor];
    [uploadBtn setTitle:@"上传" forState:UIControlStateNormal];
    [uploadBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    uploadBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [uploadBtn addTarget:self action:@selector(uploadBtnAction) forControlEvents:UIControlEventTouchUpInside];
    uploadBtn.tag = 118;
    [_addView addSubview:uploadBtn];
    
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [deleteBtn setBackgroundColor:kRedColor];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = kAppFont(Home_Big_Size);
    deleteBtn.tag = 119;
    [deleteBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:deleteBtn];
}

- (void)rightBtnAcion
{
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addControl.hidden = YES;
    _addView.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:nil];
}

- (void)addControlAction
{    
    AddShiTiCJFromUploadViewController *addVC = [[AddShiTiCJFromUploadViewController alloc] init];
    addVC.navTitle = @"实体采集";
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadTestAction{
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:dataArray];
    
    for (int i = 0; i < dataArray.count; i++)
    {
        [[YMUIUtil getInstance] hideLoadingView];
        [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
        
        NSDictionary *tempD = [dataArray objectAtIndex:i];
        if ([[tempD valueForKey:@"isSelect"] boolValue]) {
            
            //Upload_GuanJianGongXu
            
            
            NSArray *imageList = [tempD objectForKey:@"AttachList"];
            //[self resolveImages:[imageList objectAtIndex:i]];
            
            if (imageList == nil || imageList.count <= 0) {
                [[YMUIUtil getInstance] showTipViewAutoDis:@"请先确定图片已经添加"];
                [[YMUIUtil getInstance] hideLoadingView];
                
                [_myTable reloadData];
                
                [_myTable setEditing:!_myTable.editing animated:YES];
                
                _addView.hidden = YES;
                _addControl.hidden = NO;
                
                [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
                return;
            }

            
            NSMutableArray *idList = [[NSMutableArray alloc] initWithCapacity:3];
            [idList removeAllObjects];
            
            for (int j = 0; j < imageList.count; j ++) {
                
                //[hImageView setImage:tempImage];
                NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
                NSData* imageData = [imageList objectAtIndex:j];//UIImagePNGRepresentation(tempImage);
                
                NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                
                NSString* documentsDirectory = [paths objectAtIndex:0];
                
                // Now we get the full path to the file
                
                NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];
                
                // and then we write it out
                TMP_UPLOAD_IMG_PATH=fullPathToFile;
                NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                NSLog(@"===new fullPathToFile===%@",fullPathToFile);
                NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
                
                [imageData writeToFile:fullPathToFile atomically:NO];
                
                //[self onPostData];
                
                NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
                //[dir setValue:@"save" forKey:@"m"];
                [dir setValue:[[UserInfo getInstance] getUserID] forKey:@"UserID"];
                [dir setValue:[[UserInfo getInstance] getUseToken] forKey:@"UserToken"];
                NSString *url= kAppApi(Upload_File);
                NSLog(@"=======上传%@", url);
                if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){
                    [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];
                }else{
                    NSLog(@"有图标上传");
                    NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                    NSString *result =  [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];
                    NSDictionary *resultDic = [self dictionaryWithJsonString:result];
                    
                    
                    NSArray *imageID = [resultDic objectForKey:@"ResourcesList"];
                    for (NSDictionary *ggg in imageID) {
                        [idList addObject:[NSNumber numberWithInt:[[ggg valueForKey:@"ResourceId"] intValue]]];
                    }
                }
                
            }
            
            
            
            //[self loadingView];
            /*
             {
             AttachList =             (
             );
             DeptName = "\U6d66\U4e1c\U5206\U516c\U53f8";
             FinishedDate = "";
             InfoId = 1;
             InfoName = "\U5173\U952e\U5de5\U5e8f4";
             InfoRemark = sdfasdfsa;
             ProjectName = "\U6d66\U4e1c\U5927\U9053\U6574\U4fee";
             StartDate = "2016-07-22T00:00:00";
             Status = 0;
             UnitName = "\U6d66\U4e1c\U5206\U516c\U53f8";
             }
             */
            NSDictionary *bodyDic;
            float infoidF = [[tempD valueForKey:@"InfoId"] floatValue];
            if (infoidF >= 9000000000.0f) {
                
                NSDictionary *fffffDic = [tempD objectForKey:@"DeptNameInfo"];
                NSDictionary *ssssssDic = [tempD objectForKey:@"ProjectNameInfo"];
                
                bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                           [[UserInfo getInstance] getUserID],@"UserID",//UserID
                           [fffffDic valueForKey:@"OrgCode"],@"orgcode",
                           [NSNumber numberWithInt:[[ssssssDic valueForKey:@"ProjectID"] intValue]],@"projectid",
                           [tempD valueForKey:@"InfoName"],@"InfoName",
                           [tempD valueForKey:@"InfoRemark"],@"InfoRemark",
                           idList,@"InfoAttachList",
                           nil];
            }else{
                bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                           [[UserInfo getInstance] getUserID],@"UserID",//UserID
                           [NSNumber numberWithInt:[[tempD valueForKey:@"InfoId"] intValue]],@"InfoId",
                           [tempD valueForKey:@"InfoName"],@"InfoName",
                           [tempD valueForKey:@"InfoRemark"],@"InfoRemark",
                           idList,@"InfoAttachList",
                           nil];
            }
            //Upload_Task
            
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            //[manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
            //[manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
            
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            [manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
            [manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
            [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            
            
            [[YMUIUtil getInstance] hideLoadingView];
            [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
            
            NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(Upload_ShiTiQKCJ)];
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"url =  %@", urlStr);
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:bodyDic];
            NSLog(@"bodybodybody====%@", [tempDic description]);
            
            [manager POST:urlStr parameters:tempDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
                NSLog(@"获取到的数据为：%@",jsonDict);
                if ([[YMNetDataUtil getSuccessState:jsonDict] intValue] == 1){
                    [tempArray removeObject:tempD];
                    
                    dataArray = tempArray;
                    
                    [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:ShiTiQKCJ_Save];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    dataArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:ShiTiQKCJ_Save];
                    
                    [_myTable reloadData];
                    
                }
                NSLog(@"========error%@",[jsonDict valueForKey:@"Error"]);
                [[YMUIUtil getInstance] hideLoadingView];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"发生错误！%@",error);
                [[YMUIUtil getInstance] hideLoadingView];
            }];
        }
        
        
    }
    
    [_myTable reloadData];
    
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addView.hidden = YES;
    _addControl.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
}

- (void)uploadBtnAction{
    //Upload_ShiTiQKCJ
    [[YMUIUtil getInstance] hideLoadingView];
    [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
    
    //[NSThread sleepForTimeInterval:1.0f];
    
    BOOL isSelect = NO;
    
    for (int i = 0; i < dataArray.count; i++)
    {
        NSDictionary *tempD = [dataArray objectAtIndex:i];
        if ([[tempD valueForKey:@"isSelect"] boolValue]) {
            isSelect = YES;
        }
    }
    if (!isSelect) {
        [[YMUIUtil getInstance] hideLoadingView];
        
    }
    
    [self performSelector:@selector(uploadTestAction) withObject:nil afterDelay:1.0f];
    
    
    
}

- (void)btnAction:(UIButton*)sender
{
    switch (sender.tag) {
        case 116:
        {
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        case 118://提交
        {
            //Upload_ShiTiQKCJ
            //            [self hideLoadingView];
            //            [self showLoadingWithTitle:@"加载中..."];
            //
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:dataArray];
            //
            //            BOOL isSelect = NO;
            //
            //            for (int i = 0; i < dataArray.count; i++)
            //            {
            //                NSDictionary *tempD = [dataArray objectAtIndex:i];
            //                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
            //                    isSelect = YES;
            //                }
            //            }
            //            if (!isSelect) {
            //                [self hideLoadingView];
            //            }
            for (int i = 0; i < dataArray.count; i++)
            {
                NSDictionary *tempD = [dataArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    
                    //Upload_GuanJianGongXu
                    [[YMUIUtil getInstance] hideLoadingView];
                    [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
                    
                    NSArray *imageList = [tempD objectForKey:@"AttachList"];
                    //[self resolveImages:[imageList objectAtIndex:i]];
                    
                    NSMutableArray *idList = [[NSMutableArray alloc] initWithCapacity:3];
                    [idList removeAllObjects];
                    
                    for (int j = 0; j < imageList.count; j ++) {
                        
                        //[hImageView setImage:tempImage];
                        NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
                        NSData* imageData = [imageList objectAtIndex:j];//UIImagePNGRepresentation(tempImage);
                        
                        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                        
                        NSString* documentsDirectory = [paths objectAtIndex:0];
                        
                        // Now we get the full path to the file
                        
                        NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];
                        
                        // and then we write it out
                        TMP_UPLOAD_IMG_PATH=fullPathToFile;
                        NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                        NSLog(@"===new fullPathToFile===%@",fullPathToFile);
                        NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
                        
                        [imageData writeToFile:fullPathToFile atomically:NO];
                        
                        //[self onPostData];
                        
                        NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
                        //[dir setValue:@"save" forKey:@"m"];
                        [dir setValue:[[UserInfo getInstance] getUserID] forKey:@"UserID"];
                        [dir setValue:[[UserInfo getInstance] getUseToken] forKey:@"UserToken"];
                        NSString *url= kAppApi(Upload_File);
                        NSLog(@"=======上传%@", url);
                        if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){
                            [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];
                        }else{
                            NSLog(@"有图标上传");
                            NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                            NSString *result =  [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];
                            NSDictionary *resultDic = [self dictionaryWithJsonString:result];
                            
                            
                            NSArray *imageID = [resultDic objectForKey:@"ResourcesList"];
                            for (NSDictionary *ggg in imageID) {
                                [idList addObject:[NSNumber numberWithInt:[[ggg valueForKey:@"ResourceId"] intValue]]];
                            }
                        }
                        
                    }
                    
                    
                    
                    //[self loadingView];
                    /*
                     {
                     AttachList =             (
                     );
                     DeptName = "\U6d66\U4e1c\U5206\U516c\U53f8";
                     FinishedDate = "";
                     InfoId = 1;
                     InfoName = "\U5173\U952e\U5de5\U5e8f4";
                     InfoRemark = sdfasdfsa;
                     ProjectName = "\U6d66\U4e1c\U5927\U9053\U6574\U4fee";
                     StartDate = "2016-07-22T00:00:00";
                     Status = 0;
                     UnitName = "\U6d66\U4e1c\U5206\U516c\U53f8";
                     }
                     */
                    
                    //Upload_Task
                    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                             [[UserInfo getInstance] getUserID],@"UserID",//UserID
                                             [NSNumber numberWithInt:[[tempD valueForKey:@"InfoId"] intValue]],@"InfoId",
                                             [tempD valueForKey:@"InfoName"],@"InfoName",
                                             [tempD valueForKey:@"InfoRemark"],@"InfoRemark",
                                             idList,@"InfoAttachList",
                                             nil];
                    
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    //[manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
                    //[manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
                    
                    manager.requestSerializer = [AFJSONRequestSerializer serializer];
                    manager.responseSerializer = [AFJSONResponseSerializer serializer];
                    [manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
                    [manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
                    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(Upload_ShiTiQKCJ)];
                    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"url =  %@", urlStr);
                    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:bodyDic];
                    NSLog(@"bodybodybody====%@", [tempDic description]);
                    
                    [manager POST:urlStr parameters:tempDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSDictionary *jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
                        NSLog(@"获取到的数据为：%@",jsonDict);
                        if ([[YMNetDataUtil getSuccessState:jsonDict] intValue] == 1){
                            [tempArray removeObject:tempD];
                            
                            dataArray = tempArray;
                            
                            [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:ShiTiQKCJ_Save];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                            dataArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:ShiTiQKCJ_Save];
                            
                            [_myTable reloadData];
                            
                        }
                        NSLog(@"========error%@",[jsonDict valueForKey:@"Error"]);
                        [[YMUIUtil getInstance] hideLoadingView];
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"发生错误！%@",error);
                        [[YMUIUtil getInstance] hideLoadingView];
                    }];
                }
                
                
            }
            
            [_myTable reloadData];
            
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
            
            
        }
            break;
        case 119: //删除
        {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:dataArray];
            for (int i = 0; i < dataArray.count; i++)
            {
                NSDictionary *tempD = [dataArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    //[tempArray replaceObjectAtIndex:i withObject:@""];
                    [tempArray removeObject:tempD];
                }
            }
            dataArray = tempArray;
            
            [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:ShiTiQKCJ_Save];
            [[NSUserDefaults standardUserDefaults] synchronize];
            dataArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:ShiTiQKCJ_Save];
            
            [_myTable reloadData];
            
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        default:
            break;
    }
}

- (NSString *)generateUuidString
{
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
    // transfer ownership of the string
    // to the autorelease pool
    //[uuidString autorelease];
    
    // release the UUID
    CFRelease(uuid);
    
    return uuidString;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


- (void)initTableView
{
    CGRect frame = CGRectMake(0, 0.0f, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-kTabHeight);
    _myTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.footer.hidden = YES;
    _myTable.header.hidden = YES;
    _myTable.allowsSelectionDuringEditing = YES;
    [self.view addSubview:_myTable];
}

- (void)initTableHeaderView
{
    _headerView = [[UIView alloc] init];
    _headerView.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth, 40.0f);
    _headerView.backgroundColor = kWhiteColor;
    _myTable.tableHeaderView = _headerView;
    
    UIView *lineView0 = [[UIView alloc] init];
    lineView0.frame = CGRectMake(0.0f, 40.0f-0.5f, kDeviceWidth, 0.5f);
    lineView0.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView0];
    
    
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.frame = CGRectMake(kDeviceWidth/3.0f, 0.0f, 0.5f, 40.0f-0.5f);
    lineView1.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView1];
    
    
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, 0.5f, 40.0f-0.5f);
    lineView2.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView2];
    
    UIControl *lbl0Control = [[UIControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    //lbl0Control.tag = 116;
    //[lbl0Control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl0Control];
    
    UIControl *lbl1Control = [[UIControl alloc] initWithFrame:CGRectMake(kDeviceWidth/3.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    //lbl1Control.tag = 118;
    //[lbl1Control addTarget:self action:@selector(lbl1ControlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl1Control];
    
    UIControl *lbl2Control = [[UIControl alloc] initWithFrame:CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    //lbl2Control.tag = 119;
    //[lbl2Control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl2Control];
    
    //ic_down@2x.png
    UILabel *lbl0 = [[UILabel alloc] init];
    lbl0.frame = CGRectMake(0.0, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl0.font = kAppFont(Home_Small_Size+2.0f);
    lbl0.textColor = kBlackColor;
    lbl0.text = @"公司";
    lbl0.textAlignment = NSTextAlignmentCenter;
    [lbl0Control addSubview:lbl0];
    
    UIImageView *arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl0Control addSubview:arrowImageView];
    
    UILabel *lbl1 = [[UILabel alloc] init];
    lbl1.frame = CGRectMake(0.0f, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl1.font = kAppFont(Home_Small_Size+2.0f);
    lbl1.textColor = kBlackColor;
    lbl1.text = @"项目";
    lbl1.textAlignment = NSTextAlignmentCenter;
    [lbl1Control addSubview:lbl1];
    
    UIImageView *arrowImageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView1.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl1Control addSubview:arrowImageView1];
    
    
    UILabel *lbl2 = [[UILabel alloc] init];
    lbl2.frame = CGRectMake(0.0f, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl2.font = kAppFont(Home_Small_Size+2.0f);
    lbl2.textColor = kBlackColor;
    lbl2.text = @"全部工序";
    lbl2.textAlignment = NSTextAlignmentCenter;
    [lbl2Control addSubview:lbl2];
    
    UIImageView *arrowImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView2.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl2Control addSubview:arrowImageView2];
}

//- (void)controlAction:(UIControl*)sender
//{
//    switch (sender.tag) {
//        case 116:
//        {
//            SelectCompanyAndProjectViewController *selectVC = [[SelectCompanyAndProjectViewController alloc] init];
//            [self.navigationController pushViewController:selectVC animated:YES];
//        }
//            break;
//        case 118:
//        {
//            SelectCompanyAndProjectViewController *selectVC = [[SelectCompanyAndProjectViewController alloc] init];
//            [self.navigationController pushViewController:selectVC animated:YES];
//        }
//            break;
//        case 119:
//        {
//            ShiGongStatusViewController *shiGongVC = [[ShiGongStatusViewController alloc] init];
//            shiGongVC.delegate = self;
//            [self.navigationController pushViewController:shiGongVC animated:YES];
//        }
//            break;
//
//        default:
//            break;
//    }
//}


- (void)passSelectStatus:(NSDictionary *)tempDic{
    
}


#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (nil == dataArray) ? 0 : dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MultiSelectTableViewCell";
    ShiTiQKCJCell *cell = (ShiTiQKCJCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[ShiTiQKCJCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *ddd = [dataArray objectAtIndex:indexPath.row];
    cell.mSelected = [(NSNumber *)[ddd objectForKey:@"isSelect"] boolValue];
    [cell showWithData:ddd];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //[_selFlags moveObjectFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
}


#pragma mark -
#pragma mark Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.isEditing)
    {
        MultiSelectTableViewCell *cell = (MultiSelectTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell changeMSelectedState];
        
        NSDictionary *tempDic = [dataArray objectAtIndex:indexPath.row];
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:dataArray];
        for (int i = 0; i < tempArray.count; i++)
        {
            NSMutableDictionary *tempD = [[NSMutableDictionary alloc] initWithDictionary:[tempArray objectAtIndex:i]];
            if ([[tempDic valueForKey:@"InfoId"] intValue] == [[tempD valueForKey:@"InfoId"] intValue]) {
                //[NSNumber numberWithBool:YES], @"isSelect"
                //[tempD setValue:@"1" forKey:@"isSelect"];
                //[tempD removeObjectForKey:@"isSelect"];
                [tempD setObject:[NSNumber numberWithBool:cell.mSelected] forKey:@"isSelect"];
                [tempArray replaceObjectAtIndex:i withObject:tempD];
            }
        }
        
        dataArray = tempArray;
        
        //[_selFlags replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:cell.mSelected]];
    }
    else
    {
        NSDictionary *tempDic = [dataArray objectAtIndex:indexPath.row];
        UploadShiTiQKCJDetailViewController *GXVC = [[UploadShiTiQKCJDetailViewController alloc] initWithData:tempDic];
        GXVC.navTitle = @"详情";
        [self.navigationController pushViewController:GXVC animated:YES];
    }
}


//- (void)showLoadingWithTitle:(NSString *)title{
//    progressHUD = nil;
//    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
//    progressHUD = [[MBProgressHUD alloc] initWithWindow:window];
//    [window addSubview:progressHUD];
//    progressHUD.mode = MBProgressHUDModeIndeterminate;
//    progressHUD.delegate = nil;
//    progressHUD.labelText = title;
//    [progressHUD show:YES];
//}
//
//- (void)hideLoadingView
//{
//    if (progressHUD != nil) {
//        [progressHUD removeFromSuperview];
//        progressHUD = nil;
//    }
//}


@end
